
package com.idealighter.game.games.wknh.struct;

import com.idealighter.game.games.common.AbstractTable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * 悟空闹海桌子 .
 * 
 * @date 2016年3月7日 下午9:07:50
 *
 */
public class WknhTable extends AbstractTable {
  // 所属房间
  public final WknhRoom room;
  // 座位(数目固定)
  public final List<WknhSeat> seats;
  // 当前场景Index
  public int scenceIndex = 0;
  // 桌子中的场景id
  public final List<WknhScence> scences;
  // 牌桌leader，用来代发机器人的碰撞
  public long leader = 0;
  // 暂停发炮
  public boolean pauseFire;
  // 场景ScheduledFuture
  public ScheduledFuture<?> scenceFuture = null;

  /**
   * 构造函数 .
   * 
   * @param id .
   * @param room .
   * @param chairs .
   */
  public WknhTable(int id, WknhRoom room, int chairs, List<Integer> scences) {
    super(id);
    this.room = room;
    this.seats = Collections.unmodifiableList(createSeats(chairs));
    this.scences = Collections.unmodifiableList(createScences(scences));
  }

  /**
   * 创建座位 .
   * 
   * @param chairs .
   * @return
   */
  private List<WknhSeat> createSeats(int chairs) {
    List<WknhSeat> seats = new ArrayList<>(chairs);
    for (int i = 0; i < chairs; i++) {
      seats.add(new WknhSeat(i, this));
    }

    return seats;
  }

  /**
   * 创建场景 .
   * 
   * @param scenceDoms .
   * @return
   */
  private List<WknhScence> createScences(List<Integer> scenceIds) {
    List<WknhScence> scences = new ArrayList<>();
    for (Integer scenceId : scenceIds) {
      scences.add(new WknhScence(scenceId, this));
    }

    return scences;
  }

  /**
   * 获取seat .
   * 
   * @param order .
   * @return
   */
  public WknhSeat getSeat(int order) {

    return seats.get(order);
  }

  /**
   * 有玩家座位的数量 .
   * 
   * @return
   */
  public int playersNum() {
    int num = 0;
    for (WknhSeat s : seats) {
      if (s.getPlayerId() > 0) {
        num++;
      }
    }

    return num;
  }

  /**
   * 上一个场景 .
   * 
   * @return
   */
  public WknhScence scence() {
    return scences.get(scenceIndex % scences.size());
  }

  /**
   * 上一个场景 .
   * 
   * @return
   */
  public WknhScence preScence() {

    return scences.get((scenceIndex - 1) % scences.size());
  }

  /**
   * 下一个场景 .
   * 
   * @return
   */
  public WknhScence nextScence() {

    return scences.get((scenceIndex + 1) % scences.size());
  }

  /**
   * 重置数据 .
   */
  public void reset() {
    this.scenceIndex = 0;
    this.leader = 0;
    this.pauseFire = false;
    if (scenceFuture != null) {
      scenceFuture.cancel(false);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public WknhRoom room() {
    return room;
  }

  @Override
  public List<WknhSeat> seats() {

    return seats;
  }
}
